/**
 * 模型设置工具
 * 
 * 用于管理LLM和嵌入模型的配置
 */

import { prisma } from "@/lib/prisma";
import { getCurrentUserId } from "@/lib/auth";

// 模型类型定义
export interface ModelSettings {
  // 对话模型配置
  chatModel: {
    type: "openai" | "llama" | "custom";
    apiUrl: string;
    apiKey: string;
    model: string;
    temperature: number;
    topP: number;
    maxTokens: number;
  };
  
  // 嵌入模型配置
  embeddingModel: {
    type: "openai" | "custom";
    apiUrl: string;
    apiKey: string;
    model: string;
  };
}

// 默认模型设置
const defaultModelSettings: ModelSettings = {
  chatModel: {
    type: "openai",
    apiUrl: "https://api.openai.com/v1/chat/completions",
    apiKey: "",
    model: "gpt-4o",
    temperature: 0.7,
    topP: 1,
    maxTokens: 1000,
  },
  embeddingModel: {
    type: "openai",
    apiUrl: "https://api.openai.com/v1/embeddings",
    apiKey: "",
    model: "text-embedding-3-small",
  },
};

/**
 * 获取当前用户的模型设置
 * @returns 模型设置
 */
export async function getModelSettings(): Promise<ModelSettings> {
  try {
    const userId = getCurrentUserId();
    
    if (!userId) {
      return defaultModelSettings;
    }
    
    // 从数据库中获取用户
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
      include: {
        settings: true,
      },
    });
    
    // 如果用户没有设置或设置为空，返回默认设置
    if (!user || !user.settings || !user.settings.modelSettings) {
      return defaultModelSettings;
    }
    
    // 解析存储的JSON设置
    try {
      const modelSettings = JSON.parse(user.settings.modelSettings);
      return {
        chatModel: {
          ...defaultModelSettings.chatModel,
          ...modelSettings.chatModel,
        },
        embeddingModel: {
          ...defaultModelSettings.embeddingModel,
          ...modelSettings.embeddingModel,
        },
      };
    } catch (error) {
      console.error("解析模型设置错误:", error);
      return defaultModelSettings;
    }
  } catch (error) {
    console.error("获取模型设置错误:", error);
    return defaultModelSettings;
  }
}

/**
 * 保存用户的模型设置
 * @param settings 模型设置
 * @returns 是否保存成功
 */
export async function saveModelSettings(settings: ModelSettings): Promise<boolean> {
  try {
    const userId = getCurrentUserId();
    
    if (!userId) {
      return false;
    }
    
    // 获取用户
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
    });
    
    if (!user) {
      return false;
    }
    
    // 合并设置
    const mergedSettings = {
      chatModel: {
        ...defaultModelSettings.chatModel,
        ...settings.chatModel,
      },
      embeddingModel: {
        ...defaultModelSettings.embeddingModel,
        ...settings.embeddingModel,
      },
    };
    
    // 更新或创建设置
    await prisma.userSettings.upsert({
      where: { userId: user.id },
      update: {
        modelSettings: JSON.stringify(mergedSettings),
      },
      create: {
        userId: user.id,
        modelSettings: JSON.stringify(mergedSettings),
      },
    });
    
    return true;
  } catch (error) {
    console.error("保存模型设置错误:", error);
    return false;
  }
} 